<?php
	class ModCp_ProfileController extends Main_Controller_Action
	{
		public function init()
		{
			$this->loadTemplates('mod');
			$db = Zend_Registry::get('db');
		}
        
        public function preDispatch()
		{
			$auth = Zend_Auth::getInstance();
			if((!$auth->hasIdentity()) || ($auth->getIdentity()->level != 1))
			{
				if($this->_request->getActionName() != 'login')
				{
					$this->_redirect('/mod-cp/index/login');
				}
			}
		}
        
        public function indexAction()
        {
            $this->view->headTitle('Thông tin cá nhân');
            $profile = new ModCp_Model_Profile();
            $product = new AdminDthink_Model_Product();
            $auth = Zend_Auth::getInstance();
            $infoUser = $auth->getIdentity();
            $user_id = $infoUser->user_id;
            $this->view->data = $profile->getUserById($user_id);
            
            if($_POST['delImg'])
            {
                $update = $profile->delImg($user_id);
				if($update)
				{
					if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']))
					{
						unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
					}
					$this->view->error = 'Đã xóa ảnh thành công';
                    $this->view->data = $profile->getUserById($user_id);
				}
            }
            
            if($_POST['submit'])
            {
                $filter = new Zend_Filter_StringTrim();
                $email = $this->view->data['email'];
                $fullname = $filter->filter($this->_request->getParam('fullname'));
                $birthday = $this->_request->getParam('birthday');
                $gender = $this->_request->getParam('gender');
                $flag = true;
                
                $validation = new ModCp_Form_ValidateProfile();
                if(!$validation->validFullname($fullname))
                {
                    $this->view->errorFullname = 'Tên đầy đủ không hợp lệ';
                    $flag = false;
                }
                if($birthday != '')
                {
                    if(!$validation->validBirthday($birthday))
                    {
                        $this->view->errorBirthday = 'Ngày sinh phải đúng định dạng (Ngày-Tháng-Năm)';
                        $flag = false;
                    }
                }
                
                if($flag == true)
                {
                    $birthday = $product->convertToMysql($birthday);
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    $info = $upload->getFileInfo();
                    $avatar = $upload->getFileName('avatar', false);
                    if(!$validation->validAvatar($avatar))
                    {
                        $profile->editUser($user_id, $email, '', '', $fullname, $gender, $birthday);
                        $this->view->error = 'Đã sửa thành công';
                        $this->view->data = $profile->getUserById($user_id);
                    }
                    else
                    {
                        $upload->addValidator('Size', false, 410000)
                               ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                        if(!$upload->isValid())
        				{
   					        $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
        				}
                        else
                        {
                            preg_match('#\.([^\.]+)$#', $avatar, $matches);
      						$fileExtension  = $matches[1];
      						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
            						
      						$options = array('target' => BASE_PATH . '/public/files/user/' . $newFileName,'overwrite'=>true);
      						$upload->addFilter('Rename',$options,'avatar');
      						$upload->receive('avatar');
            						
      						$profile->editUser($user_id, $email, '', $newFileName, $fullname, $gender, $birthday);
      						if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']))
      						{
                                unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
      						}
      						$this->view->error = 'Đã sửa thành công';
                            $this->view->data = $profile->getUserById($user_id);
                        }
                    }
                }
            }
        }
		
		public function changepasswordAction()
		{
			$this->view->headTitle('Thay đổi mật khẩu');
			$profile = new ModCp_Model_Profile();
			$validation = new ModCp_Form_ValidateProfile();
			
			if($this->_request->isPost())
			{
				$oldPassword = $this->_request->getParam('oldPassword');
				$password = $this->_request->getParam('password');
				$rePassword = $this->_request->getParam('rePassword');
				$flag = true;
			
				if(!$validation->validPassword($oldPassword))
				{
					$this->view->errorOldPassword = 'Mật khẩu yêu cầu từ 6 - 32 kí tự';
					$flag = false;
				}
				if(!$validation->validPassword($password))
				{
					$this->view->errorPassword = 'Mật khẩu yêu cầu từ 6 - 32 kí tự';
					$flag = false;
				}
				if(!$validation->validPassword($rePassword))
				{
					$this->view->errorRePassword = 'Mật khẩu yêu cầu từ 6 - 32 kí tự';
					$flag = false;
				}
			
				if($flag == true)
				{
					$auth = Zend_Auth::getInstance();
					$infoUser = $auth->getIdentity();
					$user_id = $infoUser->user_id;
					$checkPassword = $profile->checkPassword($user_id, $oldPassword);
					if($checkPassword)
					{
						if($password == $rePassword)
						{
							$result = $profile->changePasswordUser($user_id, $password);
							if($result)
							{
								$this->view->error = 'Đổi mật khẩu thành công';
							}
							else
							{
								$this->view->error = 'Có lỗi xảy ra';
							}
						}
						else
						{
							$this->view->error = 'Mật khẩu mới không trùng khớp';
						}
					}
					else
					{
						$this->view->error = 'Mật khẩu không chính xác';
					}
				}
			}
		}
	}
